use std::io::Read;
use std::net::TcpStream;
use std::time::Duration;
use std::io::prelude::*;
use std::str;

fn init_sock(){
    let mut stream = TcpStream::connect("127.0.0.1:10248").expect("Couldn't connect to server...");
    // let stream_clone = stream.try_clone().expect("clone failed...");
    // stream.set_read_timeout(Some(Duration::new(5, 0))).expect("set read timeout fail...");
    stream.set_write_timeout(Some(Duration::new(5, 0))).expect("set write timeout fail...");

    // 设置异步
    // stream.set_nonblocking(true).expect("set_nonblocking call failed");

    // 发送数据
    let strtest: String = "test".to_string();
    stream.write(strtest.as_str().as_bytes()).expect("send data failed");
    let mut buffer = [0u8; 2048];
    let mut size = 0;
    loop {
        let mut clibuf = [0u8; 1024];
        match stream.read(&mut clibuf) {
				Ok(n) => {
					if n == 0 {
                        println!("read zero bytes...");
						break;
					} else {
                        //println!("recv len: {},size: {}",n,size);
                        buffer[size..size+n].copy_from_slice(&clibuf[..n]);
                        size+=n;
                        if n<1024 {
                            let data = match str::from_utf8(&buffer[0..size]) {
                                Ok(v) => v,
                                Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
                            };
						    println!("recv data: {}",data);
                            break;
                        }
					}
				},
				Err(error) => {
                    println!("read error: {}",error);
                    break;
                },
		}
    };

    println!("run end...");
}

fn main() {
    init_sock();
}
